package javango.forms.widgets;

import java.util.Map;

import javango.forms.fields.BooleanField;

public class CheckboxWidget extends WidgetBase {
	
	public CheckboxWidget() {
		this(null);
	}
	public CheckboxWidget(Map<String, Object> attrs) {
		super(attrs);
	}
	
	@Override
	public String[] valueFromMap(Map<String, String[]> map, String name) {
		if (map.containsKey(name)) {
			return super.valueFromMap(map, name);
		}
		return new String[]{"False"};
	}
	
	@Override
	public String render(String name, Object value, Map<String, Object> attrs) {
		Map<String, Object> finalAttrs = buildAttrs(attrs);
		finalAttrs.put("type", "checkbox");
		finalAttrs.put("name", name);

		if (finalAttrs.containsKey("id")) {
			finalAttrs.put("id", String.format((String)finalAttrs.get("id"), name));
		}
		
		if (value != null) {
			if (value instanceof String) {
	
			} else if (value instanceof String[]){
				String[] values = (String[])value;
				if (values.length > 0 && !"".equals(values[0])) {
					value = values[0];
				}	
			} else {
				value = value.toString();
			}
		}
		
		// TODO Allow for custom check value methods that
		Boolean result = BooleanField.checkBooleanValue(value);
		
		if (Boolean.TRUE.equals(result)) {
			finalAttrs.put("checked", null);
		}
		return String.format("<input%s />", Util.flatatt(finalAttrs));
	}
	
}
